<?php

namespace Auth\Model;

use Zend\Db\TableGateway\TableGateway;

class UsersTable
{
    protected $tableGateway;
    
    public function __construct(TableGateway $tableGateway) {
        $this->tableGateway = $tableGateway;
    }
    
    public function getUser($user_id)
    {
        $user_id = (int)$user_id;
        $rowset = $this->tableGateway->select(array('usr_id' => $user_id));
        $row = $rowset->current();
        if(!$row)
        {
            throw new \Exception("Could not find row $id");
        }
        return $row;
    }
    
    public function saveUser(Auth $auth)
    {
     
        $data = array(
            'usr_name' 				=> $auth->usr_name,
            'usr_password'  		=> $auth->usr_password,
            'usr_email'  			=> $auth->usr_email,
            'usrl_id'  				=> $auth->usrl_id,
            'lng_id'  				=> $auth->lng_id,
            'usr_active'  			=> $auth->usr_active ? $auth->usr_active : 0,
            'usr_question'  		=> $auth->usr_question,
            'usr_answer'  			=> $auth->usr_answer,
            'usr_picture'  			=> $auth->usr_picture,
            'usr_password_salt' 	=> $auth->usr_password_salt,
            'usr_registration_date' => $auth->usr_registration_date,
            'usr_registration_token'=> $auth->usr_registration_token,
			'usr_email_confirmed'	=> $auth->usr_email_confirmed,
        );
        
        $user_id = (int)$auth->usr_id;
        if($user_id == 0)
        {
            $this->tableGateway->insert($data);
        }
        else
        {
            if ($this->getUser($user_id)) {
                $this->tableGateway->update($data , array('usr_id' => $user_id));
            }
            else
            {
                throw new \Exception('Form id does not exist');
            }
        }
    }
}

